<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>无限滚动加载更多内容</title>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }
        ::-webkit-scrollbar {
            width: 5px;
            height: 5px;
            background-color: blue;
        }
        .page-container {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }
        .infinite-scrolling {
            width: 300px;
            height: 300px;
            padding: 5px;
            overflow: auto;
            background-color: #eee;
        }
        .item {
            height: 20px;
            background-color: lightblue;
            margin-bottom: 10px;
        }
        #sentinel {
            height: 1px;
            background-color: blue;
        }
    </style>
</head>
<body>
<div class="page-container">
    <div id="infinite-scrolling" class="infinite-scrolling">
        <div id="list" class="list">
            <div class="item">Item 1</div>
            <div class="item">Item 2</div>
            <div class="item">Item 3</div>
            <!-- 更多内容 -->
        </div>
        <div id="sentinel"></div>
    </div>
</div>
<script>
    const infiniteScrolling = document.getElementById('infinite-scrolling');
    const list = document.getElementById('list');
    const sentinel = document.getElementById('sentinel');

    const infiniteObserver = new IntersectionObserver((entries) => {
        console.log(entries[0].isIntersecting);
        if (entries[0].isIntersecting) {
            if(list.children.length >= 20) return;
            loadMoreItems();
        } else {
            console.log('不在视口');
        }
    }, {
        root: infiniteScrolling,
        rootMargin: "0px",
        threshold: 0  // 交叉率：0表示完全进入视口，0.5表示元素50%离开视口，1表示完全离开视口。
    });

    infiniteObserver.observe(sentinel);

    function loadMoreItems() {
        for (let i = 0; i < 9; i++) {
            const item = document.createElement('div');
            item.className = 'item';
            item.textContent = `Item ${list.children.length + 1}`;
            list.appendChild(item);
        }
    }
</script>
</body>
</html>

